package com.tuanzi.loan.business.repository.common.impl;

import com.tuanzi.loan.vo.response.channel.SecondaryChannelGroupResponse;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

import static com.tuanzi.loan.generated.jooq.loan.tables.SecondaryChannelGroup.SECONDARY_CHANNEL_GROUP;

@Repository
public class SecondaryChannelGroupRepository {

	@Autowired
	private DSLContext dslContext;

	public String findNameById(Integer id) {
		return dslContext.select(SECONDARY_CHANNEL_GROUP.CHANNEL_NAME).from(SECONDARY_CHANNEL_GROUP)
				.where(SECONDARY_CHANNEL_GROUP.ID.eq(id))
				.fetchOneInto(String.class);
	}

	public List<SecondaryChannelGroupResponse> findByPrimaryChannelGroup(Integer primaryChannelGroup) {
		return dslContext.select(SECONDARY_CHANNEL_GROUP.fields()).from(SECONDARY_CHANNEL_GROUP)
				.where(SECONDARY_CHANNEL_GROUP.PRIMARY_CHANNEL_GROUP.eq(primaryChannelGroup))
				.fetchInto(SecondaryChannelGroupResponse.class);
	}

	public List<SecondaryChannelGroupResponse> findAll() {
		return dslContext.select(SECONDARY_CHANNEL_GROUP.fields()).from(SECONDARY_CHANNEL_GROUP)
				.fetchInto(SecondaryChannelGroupResponse.class);
	}

	public void insert(SecondaryChannelGroupResponse response) {
		dslContext.insertInto(SECONDARY_CHANNEL_GROUP, SECONDARY_CHANNEL_GROUP.CHANNEL_NAME, SECONDARY_CHANNEL_GROUP.PRIMARY_CHANNEL_GROUP)
				.values(response.getChannelName(), response.getPrimaryChannelGroup()).execute();
	}

	public boolean existByChannelName(String channelName) {
		return dslContext.select(SECONDARY_CHANNEL_GROUP.CHANNEL_NAME.count()).from(SECONDARY_CHANNEL_GROUP)
				.where(SECONDARY_CHANNEL_GROUP.CHANNEL_NAME.eq(channelName))
				.fetchOneInto(Integer.class) > 0;
	}
}
